<template>
	<view class="page">
		<cu-custom :bgColor="'bg-' + theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">房间</block>
		</cu-custom>
		<!-- <x-video ref="myVideo" src="https://v-cdn.zjol.com.cn/276990.mp4"></x-video> -->
		<view class="sticky" :style="{ top: CustomBar + 'px' }">
			<view>
				<!-- :style="{ width: isCover ? '' : '100%' }" -->
				<video
					ref="video"
					id="video"
					style="width: 100%"
					:src="liveUrl"
					:poster="liveInfo.stopImage"
					:mobilenet-hint-type="1"
					:show-play-btn="isPlayBackShowControls"
					:play-strategy="1"
					:http-cache="true"
					:show-center-play-btn="isPlayBackShowControls"
					@loadedmetadata="loadeddata"
					:enable-progress-gesture="isPlayBackShowControls"
					:muted="notification"
					:controls="controls"
					@pause="pauseVideo"
					@ended="videoEnd"
					@timeupdate="videoTimeUpdateEvent"
					:custom-cache="true"
					v-if="isHide">
					<view class="kadun" v-if="!isPlay && !remainingTime">加载中...</view>
					<view class="tool" v-if="!isPlayBackShowControls">
						<view class="tool" v-if="status != 0">
							<view class="tips" v-if="status == 1">
								还有
								<countDown :outTime="remainingTime" textColor="#fff" @countDownDone="timeOut" />
								开始
							</view>
						<!-- 	<view class="tips" v-if="status == '2'">直播已结束</view> -->
						</view>
						<view
							v-else
							class="tool"
							@tap.stop="tool"
							:style="isShowTool || !isPlay ? 'background:#00000090' : ''">
							<view class="play" v-if="isPlayBack == 1">
								<text class="cuIcon-playfill play-icon" v-if="!isPlay" @tap.stop="play"></text>
								<text class="cuIcon-stop play-icon" v-if="isShowTool" @tap.stop="stop"></text>
							</view>
							<view
								class="jump-ad"
								v-if="isPlay && isAdPlay && liveInfo.adJump == 1 && liveInfo.adType == 1"
								@tap.stop="adJump"
								>跳过广告</view
							>
							<view v-else class="watch-num" v-if="isPlayBack != 1 && !isCover"
								>观众|{{watchNum}}</view
							>

							<view class="cover" v-if="isShowTool">
								<!-- <text
								class="cuIcon-notificationforbidfill full"
								v-if="notification"
								@tap.stop="sound(false)"
								style="margin-right: 20rpx"></text>
							<text
								class="cuIcon-notificationfill full"
								@tap.stop="sound(true)"
								v-else
								style="margin-right: 20rpx"></text> -->
								<text @tap.stop="cover" class="cuIcon-full full"></text>
							</view>
						</view>
					</view>
				</video>
			</view>
			<view class="live flex-s-b">
				<view class="flex align-center">
					<view class="avtar">
						<image :src="liveInfo.coverImage" mode="scaleToFill" />
					</view>
					<view class="flex1">
						{{ liveInfo.liveName }}
					</view>
				</view>
				<view
					v-if="userInfo.tzFlag == '1' && isPlayBack != 1"
					@tap.stop="$goUrl('/pages/live/real-time/index?liveId=' + liveId)"
					class="text-blue">
					<text class="cuIcon-my"></text>
					<text class="ml10">实时用户</text>
				</view>
				<like-button
					v-if="liveInfo.likeOpen == '1'"
					@handleClick="handleClick"
					:site="dzSite"
					:throttle="20"
					ref="likeBtn">
					<view class="dz">
						<!-- <text class="cuIcon-like text-red f36 mr10" v-if="isDz"></text> -->
						<text class="cuIcon-likefill text-red f36 mr10"></text>
						<text>{{ dzNumUnit }}</text>
					</view>
				</like-button>
			</view>
			<scroll-view scroll-x class="bg-white nav collection-types mt10">
				<view class="flex text-center">
					<view
						v-if="item.value != '4' || userInfo.tzFlag == '1' || userInfo.tzFlag == '2'"
						:class="
							'cu-item flex-sub ' + (item.value == tabCur ? 'cur text-' + theme.themeColor : '')
						"
						v-for="(item, index) in tab"
						:key="index"
						@tap.stop="tabSelect(item)">
						{{ item.title }}
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="p-all20 feature1" style="padding-bottom: 120rpx" v-if="tabCur == 1">
			<view class="message-box">
				<view v-for="(item, index) in messageList" :key="index" class="mt30">
					<!-- <text>{{ item.nickName }}:</text> -->
					{{ item.text }}
				</view>
			</view>
			<view class="chat" v-if="tabCur == 1">
				<input
					class="bottom cu-btn inp mr10 text-center"
					:disabled="liveInfo.chatOpen != '1' || isPlayBack == 1"
					:placeholder="liveInfo.chatOpen != '1' || isPlayBack == 1 ? '全员禁言中' : '请输入'"
					v-model="messageIpt" />
				<button
					:disabled="liveInfo.chatOpen != '1' || isPlayBack == 1"
					@tap.stop="sendMsg"
					class="cu-btn"
					:class="'bg-' + theme.themeColor">
					发送
				</button>
			</view>
		</view>
		<view class="feature p-all20" style="padding-bottom: 170rpx">
			<!-- :style="'height:' + (navHeight - 30) * 2 + 'rpx'" -->
			<view class="answer" scroll-y v-if="tabCur == 2">
				<block v-if="!showMask">
					<view class="item" v-for="(item, index) in liveInfo.liveUserTopicRecordList" :key="index" v-if="liveInfo.liveUserTopicRecordList.length && status != 2">
						<view class="bg-white f34 blod pt20 pb20">题目:{{ item.content }}</view>
						<view
							v-for="(val, i) in item.optionItem"
							:key="i"
							class="answer-item flex-s-b"
							:class="
								item.userAnswer.isRight == '1' && item.userAnswer.value == val.option
									? 'select'
									: item.userAnswer.isRight == '0' && item.userAnswer.value == val.option
									? 'close'
									: item.userAnswer.value == val.option
									? 'select'
									: ''
							"
							@tap="selectAnswer(item, val)">
							<text>{{ val.option }}:{{ val.content }}</text>
							<text class="cuIcon-check f30" v-if="item.userAnswer.value == val.option && item.userAnswer.isRight != '0'" style="color: #36d536"></text>
							<text class="cuIcon-close f30" v-if="item.userAnswer.value == val.option && item.userAnswer.isRight == '0'" style="color: #ff0000"></text>
						</view>

						<button class="cu-btn submit mt20" :class="'bg-' + theme.themeColor" @tap="submitAnswer(item)" v-if="!item.userAnswer.isRight" :disabled="submitting">提交答案</button>
					</view>
					<view :class="'cu-load bg-gray ' + (false ? 'loading' : 'over')"></view>
				</block>
				<view class="mask" v-else>
					<input class="input" placeholder="输入昵称开始答题" type="nickname" v-model="nickName" />
				</view>
			</view>
			<view class="" v-if="tabCur == 3">
				<view class="feature p-all20" style="padding-bottom: 170rpx">
					<rich-text :nodes="liveInfo.introduce"></rich-text>
				</view>
			</view>
			<view class="bang" v-if="tabCur == '4'">
				<view class="bang-list">
					<view class="bang-item flex-s-b p-all20" v-for="(item, index) in bangList" :key="index">
						<view class="left flex align-center">
							<text>{{ index + 1 }}</text>
							<view class="tou">
								<image v-if="item.headimgUrl" :src="item.headimgUrl" mode="scaleToFill" />
								<view class="tou-text" v-else>头</view>
							</view>
							<view class="">{{ item.tzUserName }}</view>
						</view>
						<view class="right">
							<text>邀请</text>
							<text class="text-blue">{{ item.userNum }}</text>
							<text>人</text>
						</view>
					</view>
					<view :class="'cu-load ' + (loadmore ? 'loading' : 'over')"></view>
					<view class="self flex-s-b pl40 pr40 pb50 pt20 bg-white">
						<view class="left flex align-center">
							<view class="tou">
								<image v-if="bangSelf.headimgUrl" :src="bangSelf.headimgUrl" mode="scaleToFill" />
								<view class="tou-text" v-else>头</view>
							</view>
							<view class="">{{ bangSelf.tzUserName }}</view>
							<view class="">
								<text>邀请数:</text>
								<text>{{ bangSelf.userNum }}</text>
							</view>
						</view>
						<button class="cu-btn border-radius" :class="'bg-' + theme.themeColor" open-type="share">邀请</button>
					</view>
				</view>
			</view>
		</view>
		<!-- 优惠券弹窗 -->
		<view>
			<uni-popup ref="coupon" type="center" border-radius="10px">
				<view class="coupon-image">
					<image
						src="../../static/public/img/28251772cb5610f45628e11fdfd54e6.png"
						mode="widthFix" />
				</view>
				<view class="coupon-content">
					<view class="title">领取优惠券</view>
					<view class="name">
						{{ liveInfo.liveCouponInfo.couponName || "" }}
					</view>
					<view class="lingqu" @tap.stop="getCoupon"></view>
				</view>

				<!-- <view class="bg-white p-all20 border-radius coupon-box">
					<view class="f40 text-bold text-center">优惠券</view>
					<view class="bg-white flex1 mt40 f32">{{ liveInfo.liveCouponInfo.couponName }}</view>
					<button style="width: 100%" :class="'bg-' + theme.backgroundColor" @tap.stop="getCoupon">
						立即领取
					</button>
				</view> -->
			</uni-popup>
		</view>
		<!-- 抽奖弹窗 -->
		<view>
			<uni-popup ref="draw" type="center" border-radius="10px">
				<view class="draw-bg">
					<image src="../../static/public/img/darw-bg.png" mode="widthFix"></image>
					<view class="darw-content">
						<view class="content">
							<view class="item" v-for="(item, index) in liveInfo.liveLotterySetList" :key="index">
								<view class="mr10">{{ index + 1 }}</view>
								<view class="mr10 name text-line1">{{ item.name }}</view>
								<view class="">共{{ item.qty }}</view>
							</view>
						</view>
					</view>
					<view class="draw-btn" @tap.stop="setDraw"></view>
				</view>
			</uni-popup>
		</view>
		<!-- <view class="draw-suspension"></view> -->
		<view>
			<uni-popup ref="answer" type="center" border-radius="10px">
				<view class="text-center">
					<image
						style="width: 320rpx; height: 340rpx"
						src="../../static/public/img/jiangpin.png"
						mode="widthFix"></image>
					<view class="mt10 f38 p-all20 border-radius text-red">{{
						drawOverAnswer || "恭喜您全部答对！"
					}}</view>
				</view>
			</uni-popup>
		</view>
		<view>
			<uni-popup ref="drawOver" type="center" border-radius="10px">
				<view class="draw-box border-radius">
					<view class="title">恭喜您抽中神秘奖励</view>
					<view class="name">
						<text class="nowrap">{{ drawOverPrize || "" }}</text>
					</view>

					<view class="btn" @tap.stop="$refs.drawOver.close()">开心收下</view>
				</view>
			</uni-popup>
		</view>
	
	</view>
</template>
<script>
import videoLive from "../../components/video-live/index.vue";
import countDown from "../../components/count-down/index.vue";
import XVideo from "../../uni_modules/x-video/components/x-video/x-video.vue";
import __config from "config/env";

const app = getApp();
import util from "utils/util";
import api from "utils/api";
import likeButton from "../../uni_modules/like-button/components/like-button/like-button.vue";
export default {
	components: {
		videoLive,
		XVideo,
		countDown,
		likeButton,
	},
	data() {
		return {
			submitting: false,
			bangList: [],
			bangSelf: {},
			bangPage: {
				current: 1,
				size: 10,
				total: 0,
			},
			options: {
				0: "A",
				1: "B",
				2: "C",
				3: "D",
				4: "E",
			},
			theme: app.globalData.theme, //全局颜色变量
			videoContext: null,
			durationTime: 0,
			time: 0,
			controls: false,
			isPlay: false,
			isShowTool: false,
			isCover: false,
			isHide: true,
			notification: false,
			startTime: "",
			endTime: "",
			status: "0",
			setTimer: null,
			intervalTimer: null,
			remainingTime: 0,
			liveId: "",
			liveInfo: {
				// 题目默认值
				// liveUserTopicRecordList:[{
				// 	content:'呵呵呵呵呵',
				// 	optionItem:[
				// 		{
				// 			option:'1',
				// 			content:'1',
				// 	    },
				// 		{
				// 			option:'1',
				// 			content:'1',
				// 		},
				// 		{
				// 			option:'1',
				// 			content:'1',
				// 		}
				// 	]
				// }] 
			},
			liveUrl: "",
			isAdPlay: false,
			isPlayBack: "2",
			socketTask: null,
			userInfo: {},
			dzSite: {
				x: "",
				y: "",
			},
			tabCur: "1",
			tab: [
				{
					title: "聊天室",
					value: "1",
				},
				{
					title: "活动",
					value: "2",
				},
				{
					title: "邀请榜",
					value: "4",
				},
				{
					title: "介绍",
					value: "3",
				},
			],
			pH: 0, //窗口高度
			navHeight: 0, //元素的所需高度
			watchNum: 0, //在线人数
			dzNum: 0, //点赞数
			messageList: [],
			messageIpt: "",
			tzId: "",
			videoCurrentTime: 0,
			playBackTime: 0,
			sendParam: {
				userId: "",
				nickName: "",
				headimgUrl: "",
				liveId: "",
				liveName: "",
				virtuallyUserNo: "",
				msgType: "",
				message: "",
			},
			isPlayBackShowControls: false,
			drawOverPrize: "",
			kadun: null,
			isKadun: false,
			isConnected: null,
			CustomBar: this.CustomBar,
			loadmore: true,
			drawOverAnswer: "",
			showMask:false,//游客蒙层
			nickName:'',//游客昵称更新
			answerCur:{}//选中答题
		};
	},
	watch: {
		remainingTime(val){
			this.stop();
			if(val<2000){
				this.remainingTime=0
				this.play()
			}
		},
		isShowTool(val) {
			if (val) {
				this.timeOutCloseTool(1500);
			}
		},
		//获取用户昵称，需要二次写入后端和本地缓存
		nickName(val){
			// let user = uni.getStorageSync('user_info')
			// user.nickName = val
			// uni.setStorageSync('user_info', user)
			// this.user.nickName = val
			// this.showMask = false
			// this.getLiveList()
			this.updateUserName(val)
		}
	},
	computed: {
		dzNumUnit() {
			let str = "";
			if (this.dzNum < 1000) {
				str = this.dzNum;
			} else if (this.dzNum < 10000) {
				str = (this.dzNum / 1000).toFixed(1) + "k";
			} else if (this.dzNum < 100000) {
				str = (this.dzNum / 10000).toFixed(1) + "w";
			} else {
				str = "10w+";
			}
			return str;
		},
	},
	onShareAppMessage(res) {
		if (this.liveInfo.forward == 1) {
			return {
				title: this.liveName, //自定义标题
				path:
					"/pages/home/index?liveId=" + this.liveInfo.id + "&code=" + this.userInfo.id + "&type=1",
				imageUrl: this.liveInfo.stopImage, //自定义展示图片
			};
		} else {
			wx.updateShareMenu({
				isPrivateMessage: true,
				withShareTicket: true,
			});
			return {
				title: this.liveName, //自定义标题
				path:
					"/pages/home/index?liveId=" + this.liveInfo.id + "&code=" + this.userInfo.id + "&type=1",
				imageUrl: this.liveInfo.stopImage, //自定义展示图片
			};
		}
	},
	onShow() {
		// this.intervalStaus();
	},
	onLoad(options) {
		if (options.tzId) {
			this.tzId = options.tzId;
		}
		uni.showToast({
			title: options.tzId,
			icon: "none",
		});
		this.liveId = options.liveId;
		this.isPlayBack = options.isPlayBack || 2;
		this.userInfo = uni.getStorageSync("user_info");
		this.getLiveInfo();
		if (this.isPlayBack == 1) {
			this.PlaybackProcessingPlay();
		}
	},
	onReady() {
		// let that = this;
		this.$nextTick(() => {
			this.videoContext = uni.createVideoContext("video");
			this.NetChange();
			this.changeLive(1);
			// this.isHide = true;
		});
		// uni.getSystemInfo({
		// 	//调用uni-app接口获取屏幕高度
		// 	success(res) {
		// 		//成功回调函数
		// 		that.pH = res.windowHeight; //windoHeight为窗口高度，主要使用的是这个
		// 		let titleH = uni.createSelectorQuery().select(".answer"); //想要获取高度的元素名（class/id）
		// 		titleH
		// 			.boundingClientRect((data) => {
		// 				console.log(data, "获取元素高度");
		// 				let pH = that._data.pH;
		// 				that.navHeight = pH - data.top; //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
		// 				console.log(that.navHeight, "111111111111");
		// 			})
		// 			.exec();
		// 	},
		// });
	},

	onUnload() {
		this.$nextTick(() => {
			if (this.isPlayBack == 1) {
				this.PlaybackProcessing();
			}
			this.changeLive(2);
			this.stop();
			this.isHide = false;
			this.isCover = false;
		});
	},
	onHide() {
		console.log("离开页面");
		this.changeLive(2);
	},
	beforeDestroy() {
		this.changeLive(2);
	},
	onReachBottom() {
		if (this.loadmore) {
			this.bangPage.current++;
			// this.getPage();
		}
	},
	methods: {
		//tab栏
		tabSelect(item) {
			this.tabCur = item.value;
			
			let userInfo = uni.getStorageSync('user_info');
			if(item.value == 2 && userInfo.loginMethod == 1 ){
				this.showMask = true
				return false
			}
			this.getlive();
			if (this.tabCur == "4") {
				this.bangPage.current = 1;
				this.bangList = [];
				this.getBangList();
			}
		},
		//更新用户昵称
		updateUserName(nick){
			if(!nick){
				uni.showToast({
					title: "请先获取或填写昵称!",
					duration: 2000,
				});
				return
			}else{
				api.userInfoUpdate({
					id: this.userInfo.id,
					loginMethod: 2,	//0正常用户，1游客初始，2游客昵称授权，3游客头像授权
					nickName: nick
				}).then(res=>{
					this.showMask = false
					this.userInfo.loginMethod = 2
					uni.setStorageSync("user_info", this.userInfo);
					this.getlive();
					// this.userInfo = uni.getStorageSync("user_info");
					// uni.showToast({
					// 	title: "操作成功",
					// 	type: "success",
					// });
				})
				
			}
		},
		getBangList() {
			let para = {
				current: this.bangPage.current,
				size: this.bangPage.size,
				liveId: this.liveId,
			};
			api.getBangList(para).then((res) => {
				let obj = {
					tzUserId: res.data.tzUserId,
					tzUserName: res.data.tzUserName,
					userNum: res.data.userNum,
					headimgUrl: res.data.headimgUrl,
				};
				this.bangSelf = obj;
				let bangList = res.data.page.records;
				this.bangList = [...this.bangList, ...bangList];
				if (bangList.length < this.bangPage.size) {
					this.loadmore = false;
				}
			});
		},
		NetChange() {
			wx.onNetworkStatusChange((res) => {
				console.log(res.isConnected,'3251465345346');
				this.isConnected = res.isConnected;
				if (!res.isConnected) {
					uni.showModal({
						title: "提示",
						content: "网络异常,请检查网络状态!",
						confirmText: "退出",
						showCancel: false,
						success: ({ confirm }) => {
							uni.navigateBack({
								delta: 1,
							});
						},
					});
					this.stop();
					this.changeLive(2);
				} else {
					this.getLiveInfo();
					this.changeLive(1);
				}
				console.log(res.networkType);
			});
		},
		pauseVideo(e) {
			if (!this.isKadun && !this.isPlayBackShowControls) {
				// this.changeLive(2);
				// this.changeLive(1);
				this.isKadun = false;
			}
		},
		getCoupon() {
			api
				.liveGetCoupon({
					liveId: this.liveId,
					userId: this.userInfo.id,
					couponId: this.liveInfo.liveCouponInfo.id,
				})
				.then((res) => {
					if (res.data == 1) {
						uni.showToast({
							title: "恭喜您抢到了!",
							icon: "success",
							duration: 2000,
						});
					} else {
						uni.showToast({
							title: "很遗憾,没抢到!",
							icon: "error",
							duration: 2000,
						});
					}
					this.$refs.coupon.close();
				});
		},
		setDraw() {
			api
				.liveSetDraw({
					liveId: this.liveId,
					userId: this.userInfo.id,
				})
				.then((res) => {
					uni.showToast({
						title: "参与成功!",
						icon: "success",
						duration: 2000,
					});
					this.$refs.draw.close();
				});
		},
		setPlayBackShowControls() {
			let flag = false;
			if (this.isPlayBack == 1) {
				flag = this.liveInfo.progress == "1" ? true : false;
			} else {
				flag = false;
			}
			return flag;
		},
		PlaybackProcessing() {
			let para = {
				liveId: this.liveId,
				videoCurrentTime: this.videoCurrentTime,
			};
			let videoCurrentTimeObj = uni.getStorageSync("videoCurrentTimeObj");
			if (videoCurrentTimeObj && videoCurrentTimeObj.length) {
				let index = videoCurrentTimeObj.findIndex((el) => el.liveId == para.liveId);
				if (index != -1) {
					videoCurrentTimeObj[index].videoCurrentTime = para.videoCurrentTime;
				} else {
					videoCurrentTimeObj.push(para);
				}
			} else {
				videoCurrentTimeObj = [];
				videoCurrentTimeObj.push(para);
			}
			uni.removeStorageSync("videoCurrentTimeObj");
			uni.setStorageSync("videoCurrentTimeObj", videoCurrentTimeObj);
		},
		PlaybackProcessingPlay() {
			let videoCurrentTimeObj = uni.getStorageSync("videoCurrentTimeObj");
			if (videoCurrentTimeObj && videoCurrentTimeObj.length) {
				let index = videoCurrentTimeObj.findIndex((el) => el.liveId == this.liveId);
				let that = this;
				if (index != -1) {
					uni.showModal({
						title: "提示",
						content: "是否跳转到上次观看时间",
						success(res) {
							if (res.confirm) {
								console.log("继续播放");
								that.play({}, videoCurrentTimeObj[index].videoCurrentTime);
							} else {
								that.play();
							}
						},
					});
					this.playBackTime = videoCurrentTimeObj[index].videoCurrentTime;
				}
			}
		},
		videoTimeUpdateEvent(e) {
		
			clearTimeout(this.kadun);
			let liveTime = this.setStaus();
			let chazhi = liveTime - e.detail.currentTime;
			chazhi = chazhi > 0 ? chazhi : -chazhi;
			
			if (chazhi > 10000) {
				//视频延迟大于10s
				this.stop();
				setTimeout(()=>{
					this.play();
				},1000)
			}
			else{
				this.play()
			}
			// if(liveTime )
			this.videoCurrentTime = e.detail.currentTime;
			if (this.isPlayBackShowControls) {
				return;
			}
			this.kadun = setTimeout(() => {
				// this.changeLive(2);\
				// if (this.isPlay) {
				this.isKadun = true;
				this.stop();
				this.play();
				// }
				// this.changeLive(1);
			}, 3000);
			// let videoCurrentTime  = e.detail.currentTime
			// console.log(videoCurrentTime,'videoCurrentTime');
		},
		sendMsg() {
			if (!this.messageIpt) {
				return;
			}
			if (this.messageIpt.length > 20) {
				uni.showToast({
					title: "最多支持20个字符",
					icon: "none",
				});
				return;
			}
			this.sendParam.msgType = 2;
			this.sendParam.message = this.messageIpt;
			this.wsSend(this.sendParam);
		},
		// conversionUnit(num) {
		// 	// if (!num) {
		// 	// 	return 0;
		// 	// }
		// 	let str = "";
		// 	if (num < 1000) {
		// 		str = num;
		// 	} else if (num < 10000) {
		// 		str = (num / 1000).toFixed(1) + "k";
		// 	} else if (num < 100000) {
		// 		str = (num / 10000).toFixed(1) + "w";
		// 	} else {
		// 		str = "10w+";
		// 	}
		// 	return str;
		// },
		handleClick() {
			this.sendParam.msgType = 3;
			this.sendParam.message = "";
			this.wsSend(this.sendParam);
		},
		connectSocketInit() {
			let that = this
			console.log("6547486574869486468468",uni.getSystemInfoSync().platform=='');
			this.socketTask = uni.connectSocket({
				url:
					__config.wsPath +
					`/liveapi/imserver/${that.userInfo.tenantId}/${that.userInfo.id}/${that.liveId}`,
				success(data) {
					// console.log(__config.wsPath +`/liveapi/imserver/${that.userInfo.tenantId}/${that.userInfo.id}/${that.liveId}`)
					console.log("websocket连接成功", data);
					that.play();
				},
				fail(data){
					this.connectSocketInit()
				}
			});
			this.socketTask.onOpen((res) => {
				console.log("WebSocket连接正常打开中...！",res);
				this.play();	
			});
			this.socketTask.onClose((res) => {
				console.log("已经被关闭了");
			});
			this.socketTask.onMessage((res) => {
				this.wsMessage(res);
				console.log("收到服务器内容：" + res.data);
			});
		},
		wsMessage(res) {
			//1点赞 2评论 3在线人数
			// type=3 赋值直播间人数和点赞数
			// type=1 赋值直播间人数和点赞数
			// type=2 赋值直播间人数和评论
			let data = JSON.parse(res.data);
			let userInfo = uni.getStorageSync("user_info");
			console.log(data, "datadatadata");
			// 消息类型（1直播间人数变化（进入/退出），2直播间评论，3.直播间点赞，4发送优惠券，5直播间抽奖开启，6直播间抽奖结果，7提出直播间，8直播间公告）
			if (data.msgType == 1 || data.msgType == 2 || data.msgType == 8) {
				this.watchNum = data.liveOnlineNum;
				this.dzNum = data.liveNum;
				let obj = {
					text: data.commentContent,
					date: new Date(),
				};
				this.messageList.unshift(obj);
			}
			if (data.msgType == 3) {
				this.watchNum = data.liveOnlineNum;
				this.dzNum = data.liveNum;
			}
			if (data.msgType == 7) {
				this.stop();
				this.changeLive(2);
				this.watchNum = data.liveOnlineNum;
				this.dzNum = data.liveNum;
				uni.showModal({
					title: "提示",
					content: "您已被移出",
					showCancel: false,
					success: ({ confirm }) => {
						if (confirm) {
							uni.navigateBack();
						}
					},
				});
			}
			if (data.msgType == 4) {
				if (userInfo.tzFlag != "0") {
					return;
				}
				if (this.liveInfo.liveCouponInfo && this.liveInfo.liveCouponInfo.couponName) {
					this.$refs.coupon.open();
				}
				// if (this.liveInfo.liveLotterySetList && this.liveInfo.liveLotterySetList.length) {
				// 	this.$refs.coupon.open();
				// }
			}
			if (data.msgType == 5) {
				if (userInfo.tzFlag != "0") {
					return;
				}
				console.log("抽奖弹窗");
				if (this.liveInfo.liveLotterySetList && this.liveInfo.liveLotterySetList.length) {
					this.$refs.draw.open();
				}
			}
			if (data.msgType == 6) {
				if (userInfo.tzFlag != "0") {
					return;
				}
				this.drawOverPrize = data.commentContent;
				if (this.liveInfo.liveLotterySetList && this.liveInfo.liveLotterySetList.length) {
					this.$refs.drawOver.open();
				}
				console.log("抽奖结果弹窗");
			}

			// if (data.msgType) {
			// 	let obj = {
			// 		text: data.data,
			// 		nickName: data.nickName,
			// 		date: new Date(),
			// 	};
			// 	this.messageList.unshift(obj);
			// }
			// if (data.type == 3) {
			// 	this.watchNum = data.liveOnlineNum;
			// 	this.dzNum = data.liveNum;
			// }
			// if (data.type == 1) {
			// 	this.dzNum = data.liveNum;
			// }
			// if (data.type == "-1") {
			// 	this.stop();
			// 	this.wsClose();
			// 	uni.showModal({
			// 		title: "提示",
			// 		content: "您已被移出",
			// 		showCancel: false,
			// 		success: ({ confirm }) => {
			// 			if (confirm) {
			// 				uni.navigateBack();
			// 			}
			// 		},
			// 	});
			// }
		},
		wsClose() {
			this.socketTask.close();
		},
		wsSend(data) {
			let para = JSON.stringify(data);
			let that = this;
			this.socketTask.send({
				data: para, //我是要发送的数据
				success(res) {
					console.log("发送成功");
					that.messageIpt = "";
				},
			});
		},
		//进入离开直播间
		changeLive(type) {
			console.log(type, "type");
			console.log('进入切换播放状态');
			let user = uni.getStorageSync("user_info");
			console.log(user,'userrrrrrrrrrr');
			let para = {
				liveId: this.liveId,
				type: type,
				userId: user.id,
				userTime: util.timestampToTime(new Date()),
			};
			if (type == 1) {
				this.connectSocketInit();
			} else {
				this.wsClose();
				this.isPlay = false;
				wx.offNetworkStatusChange();
			}
			if (this.isConnected) {
				api.liveuserrecord(para).then((res) => {
					console.log(res);
				});
			}
		},
		//显示对错
		rightOrClose(item, i) {
			let str = "";
			if (item.userAnswer.isRight == "0" || item.userAnswer.isRight == "1") {
				str = item.userAnswer.isRight == "0" ? "close" : "select";
			} else {
				str = item.userAnswer.value == i ? "select" : "";
			}
			return str;
		},
		//提交答案
		submitAnswer(item) {
			if(this.remainingTime>3000){
				uni.showToast({
					title: "直播尚未开始",
					icon: "none",
				});
				return;
			}
			if(!this.userInfo.headimgUrl){
				this.$refs.avatarPop.open();
				return
			}
			if (!item.userAnswer.value) {
				uni.showToast({
					title: "请选择答案",
					icon: "none",
				});
				return;
			}
			// 设置提交状态为true
			this.submitting = true;
			let para = {
				liveId: this.liveId,
				id: item.id,
				userAnswer: item.userAnswer.value,
				answer: item.answer,
			};
			api.liveusertopicrecord(para).then((res) => {
				item.userAnswer.isRight = res.data.flag;
				if (res.data.okFlag == "1") {
					this.drawOverAnswer = res.data.msg;
					this.$refs.answer.open();
					return;
				}
				uni.showToast({
					title: res.data.msg,
					icon: "none",
					duration: 5000,
				});
			}).catch((err) => {
				item.userAnswer.isRight = "";
				uni.showToast({
					title: err || '提交失败',
					icon: "none",
					duration: 2000,
				});
			}).finally(() => {
				// 无论成功或失败，都要重置提交状态
				this.submitting = false;
				setTimeout(() => {
					this.submitting = false;
				}, 500);
			});
		},
		//选择题
		selectAnswer(item, val) {
			if (item.userAnswer && item.userAnswer.isRight) {
				return;
			}
			item.userAnswer.value = val.option;
		},
	
		//跳过广告
		adJump() {
			this.stop();
			this.liveUrl = this.liveInfo.liveUrl;
			this.startTime = this.liveInfo.startTime;
			this.isAdPlay = false;
			setTimeout(() => {
				this.play();
			}, 200);
		},
		getLiveInfo() {
			console.log(this.isPlayBack, "111111");
			if (this.isPlayBack == "1") {
				this.getPlayback();
			} else {
				this.getlive();
			}
		},
		getPlayback() {
			api.getPlayback({
					id: this.liveId,
				})
				.then((res) => {
					if (res.data.liveUserTopicRecordList && res.data.liveUserTopicRecordList.length) {
						res.data.liveUserTopicRecordList.forEach((el) => {
							el.optionItem = JSON.parse(el.optionItem);
							let userAnswer = {
								value: el.userAnswer ? el.userAnswer : "",
								isRight: "",
							};
							userAnswer.isRight = userAnswer.value
								? userAnswer.value == el.answer
									? "1"
									: "0"
								: "";
							el.userAnswer = userAnswer;
						});
					}
					res.data.introduce = res.data.introduce.replace(
						/<img/gi,
						'<img style="max-width:100%;height:auto" ',
					);

					this.liveInfo = res.data;
					this.startTime = res.data.startTime;
					this.liveUrl = res.data.liveUrl;
					this.isPlayBackShowControls = this.setPlayBackShowControls();
					// 处理ws发送内容
					// this.setSendParam();
					// if (res.data.adType == 1) {
					// 	this.isAdPlay = true;
					// }
				});
		},
		getlive() {
			api.getliveInfo(this.liveId).then((res) => {
				if (res.data.liveUserTopicRecordList && res.data.liveUserTopicRecordList.length) {
					res.data.liveUserTopicRecordList.forEach((el) => {
						el.optionItem = JSON.parse(el.optionItem);
						let userAnswer = {
							value: el.userAnswer ? el.userAnswer : "",
							isRight: "",
						};
						userAnswer.isRight = userAnswer.value
							? userAnswer.value == el.answer
								? "1"
								: "0"
							: "";
						el.userAnswer = userAnswer;
					});
				}
				res.data.introduce = res.data.introduce.replace(
					/<img/gi,
					'<img style="max-width:100%;height:auto" ',
				);
				this.liveInfo = res.data;
				this.startTime = res.data.startTime;
				this.liveUrl = res.data.liveUrl;
				// 处理ws发送内容
				this.setSendParam();
				// if (res.data.adType == 1) {
				// 	this.isAdPlay = true;
				// }
				// if (this.isPlayBack != 1) {
				// 	this.connectSocketInit();
				// }
				if (this.userInfo.isTz != 1) {
					this.bindManager();
				}
			});
		},
		setSendParam() {
			// userId: '',
			// nickName: '',
			// headimgUrl: '',
			// liveId: '',
			// liveName: '',
			// virtuallyUserNo: '',
			// msgType: '',
			// message: '
			let userInfo = uni.getStorageSync("user_info");
			this.sendParam.userId = userInfo.id;
			this.sendParam.nickName = userInfo.nickName;
			this.sendParam.headimgUrl = userInfo.headimgUrl;
			this.sendParam.liveId = this.liveId;
			this.sendParam.virtuallyUserNo = this.liveInfo.virtuallyUserNo;
			this.sendParam.liveName = this.liveInfo.liveName;
		},
		bindManager() {
			let para = {
				id: this.userInfo.id,
				managerParentId: this.tzId || "",
			};
			api.bindManager(para).then((res) => {
				console.log("绑定成功");
			}).catch((err) => {
				uni.showToast({
					title: "绑定失败",
					icon: "error",
				});
				setTimeout(() => {
					uni.navigateBack({
						delta: 1,
					});
				}, 1000);
			});
		},
		videoEnd() {
			this.wsClose();//关闭websocket
			this.stop();
			// this.setStaus();
			
			this.status = "2";
			this.isHide = false;
			this.isCover = true
			console.log(9999999999999999999)
			uni.showModal({
				title: "提示",
				content: "直播已结束",
				showCancel: false,
				success: ({ confirm }) => {
					if (confirm) {	
						uni.navigateBack();
					}
				},
			});
			// if (this.isAdPlay) {
			// 	this.liveUrl = this.liveInfo.liveUrl;
			// 	this.startTime = this.liveInfo.startTime;
			// 	this.endTime = this.liveInfo.endTime;
			// 	this.isAdPlay = false;
			// 	setTimeout(() => {
			// 		this.play();
			// 	}, 500);
			// }
		},
		timeOut() {
			this.remainingTime = 0;
			console.log(this.remainingTime, 111);
			this.play();
		},
		setStaus() {
			let startTime = new Date(this.startTime).getTime();
			let endTime = new Date(this.endTime).getTime();
			let date = new Date().getTime();
			if (startTime > date) {
				this.remainingTime = startTime - date;
				this.status = "1";
			} else if (date > endTime) {
				this.status = "2";
			} else {
				this.status = "0";
			}
			let time = ((date - startTime) / 1000).toFixed(0) - 0;
			this.time = time;
			if (this.isPlayBack == 1) {
				this.status = "0";
				this.controls = this.liveInfo.progress == "1" ? true : false;
				time = this.videoCurrentTime;
			}

			return time;
		},
		timeOutCloseTool(time) {
			clearTimeout(this.setTimer);
			this.setTimer = setTimeout(() => {
				this.isShowTool = false;
			}, time);
		},
		sound(e) {
			clearTimeout(this.setTimer);
			this.notification = e;
			this.timeOutCloseTool(1500);
		},
		tool() {
			console.log(this.isPlay, "isPlay");
			if (this.isPlay) {
				this.isShowTool = !this.isShowTool;
			}
		},
		loadeddata(e) {
			this.durationTime = e.detail.duration;
			this.endTime = util.timestampToTime(
				this.durationTime * 1000 - 0 + (new Date(this.startTime).getTime() - 0),
			);
			this.setStaus();
		},
		stop() {
			this.videoContext.pause();
			this.isPlay = false;
			this.isShowTool = false;
		},
		play(e, playBackTime) {
			
			console.log('进入播放');
			console.log(this.videoContext,'视频示例');
			if (this.remainingTime != 0) {
				return;
			}
			if (playBackTime) {
				this.videoContext.seek(playBackTime - 0);
				this.isPlay = true;
				// this.isShowTool = true;
				setTimeout(() => {
					this.videoContext.play();
				}, 10);
				return;
			}
			
			console.log("播放视频");
			// if (this.isAdPlay) {
			// 	this.liveUrl = this.liveInfo.adLink;
			// 	this.startTime = new Date().getTime();
			// }
			let time = this.setStaus();
			this.isPlay = true;
			// this.isShowTool = true;
			// this.videoContext.seek(time - 0);//导致拉动进度条闪屏
			
			setTimeout(() => {
				this.videoContext.play();
			}, 100);
		},
		cover() {
			if (this.isCover) {
				this.videoContext.exitFullScreen();
				this.isCover = false;
			} else {
				this.isCover = true;
				if (this.liveInfo.screenShow == "1") {
					this.videoContext.requestFullScreen({
						direction: 90,
					});
				} else {
					this.videoContext.requestFullScreen({
						direction: 0,
					});
				}
			}
		},
	},
};
</script>
<style lang="scss" scoped>
.tool {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

#video {
	position: relative;
}

.play {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);

	.play-icon {
		color: #fff;
		font-size: 50rpx;
	}
}

.cover {
	position: absolute;
	right: 30rpx;
	bottom: 30rpx;

	.full {
		font-size: 50rpx;
		color: #fff;
	}
}

.tips {
	color: #fff;
	padding: 10rpx;
	font-size: 30rpx;
	border-radius: 16rpx;
	border: 1rpx solid #fff;
	height: 50rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.kadun {
	color: #fff;
	padding: 10rpx;
	font-size: 30rpx;
	border-radius: 16rpx;
	height: 50rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

.jump-ad {
	position: absolute;
	top: 50rpx;
	right: 30rpx;
	color: #fff;
}

.live {
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	background-color: #fff;

	.avtar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-right: 30rpx;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}
}

.dz {
	display: flex;
	align-items: center;
	padding: 30rpx;
}

.chat {
	width: 100%;
	background-color: #fff;
}

.page {
	width: 100%;
	display: flex;
	flex-direction: column;
	.feature1 {
		flex: 1;
		.chat {
			padding: 30rpx;
			position: absolute;
			bottom: 20rpx;
			left: 0;
			right: 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.inp {
				flex: 1;
				color: #000;
				border-radius: 8rpx;
			}
		}
	}
	.feature {
		flex: 1;
		position: relative;
		.chat {
			padding: 30rpx;
			position: absolute;
			bottom: 20rpx;
			left: 0;
			right: 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.inp {
				flex: 1;
				color: #000;
				border-radius: 8rpx;
			}
		}
	}
}
.mask{background: rgba(0,0,0,.12);width: 100vw;height: 400rpx;text-align: center;padding: 30px;
	.input{margin: 30rpx auto;border-radius: 20rpx;border:1px solid #666;background: #fff;line-height: 80rpx;height: 80rpx;}
}
.answer {
	// position: absolute;
	// left: 0;
	// right: 0;
	// bottom: 30rpx;
	// top: 0;
	// overflow: auto;
	// z-index: 99;
	.item {
		margin: 20rpx;
		padding: 20rpx;
		border-radius: 16rpx;
		background-color: #fff;

		.submit {
			width: 100%;
		}

		.answer-item {
			padding: 20rpx;
			margin-top: 10rpx;
			background-color: #fff;
			border-radius: 8rpx;
		}

		.select {
			background-color: #36d53660;
		}

		.close {
			background-color: #ff000050;
		}
	}
}

.share-btn {
	&::after {
		border: none;
	}

	position: relative;
	display: block;
	margin-left: auto;
	margin-right: auto;
	padding-left: 0px;
	padding-right: 0px;
	box-sizing: border-box;
	// font-size: 18px;
	text-align: center;
	text-decoration: none;
	// line-height: 1;
	line-height: 1.35;
	// border-radius: 5px;
	-webkit-tap-highlight-color: transparent;
	overflow: hidden;
	color: #000000;
	background-color: #fff;
	width: 100%;
	height: 100%;
}

.watch-num {
	position: absolute;
	top: 50rpx;
	right: 30rpx;
	color: #fff;
}

.message-box {
	display: flex;
	flex-direction: column-reverse;
	position: absolute;
	padding: 10rpx 20rpx;
	top: 0;
	bottom: 170rpx;
	left: 0;
	right: 0;
	overflow: auto;
}

.draw-bg {
	width: 85vw;
	position: relative;

	image {
		width: 100%;
	}

	.draw-btn {
		position: absolute;
		height: 100rpx;
		left: 70rpx;
		right: 90rpx;
		bottom: 100rpx;
	}

	.darw-content {
		position: absolute;
		top: 130rpx;
		left: 70rpx;
		right: 90rpx;
		bottom: 230rpx;

		overflow-y: auto;
		color: #f4654c;

		.content {
			display: flex;
			flex-direction: column;
			padding: 10rpx 30rpx;

			.item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 20rpx;

				.name {
					flex: 1;
				}
			}
		}
	}
}

.coupon-box {
	width: 60vw;
	height: 35vh;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.coupon-image {
	position: relative;
}

.coupon-content {
	position: absolute;
	left: 50rpx;
	right: 50rpx;
	top: 160rpx;
	bottom: 100rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;

	.title {
		margin-top: 50rpx;
		font-size: 50rpx;
		color: #f4654c;
		text-align: center;
		font-weight: 600;
	}

	.name {
		font-size: 38rpx;
		color: #f4654c;
		text-align: center;
	}

	.lingqu {
		padding: 50rpx;
		margin-bottom: 50rpx;
	}
}

.draw-box {
	background-image: linear-gradient(180deg, rgb(255, 219, 207), #fff);
	padding: 50rpx;
	width: 80vw;
	margin: 0 auto;
	text-align: center;

	.title {
		font-size: 50rpx;
		color: rgb(116, 11, 2);
		font-weight: 600;
		margin-bottom: 80rpx;
	}

	.name {
		text-align: center;
		font-size: 36rpx;
		color: #fff;
		width: 100%;
		margin: 0 auto;
		height: 160rpx;
		background-color: rgb(254, 111, 26);
		border-radius: 30rpx;
		line-height: 160rpx;
		padding: 0 20rpx;
		overflow: auto;
	}

	.btn {
		margin: 0 auto;
		margin-top: 100rpx;
		width: 100%;
		border-radius: 60rpx;
		height: 100rpx;
		color: #fff;
		line-height: 100rpx;
		font-size: 38rpx;
		font-weight: 600;
		background-color: rgb(254, 111, 26);
	}
}

.sticky {
	position: sticky;
	z-index: 70;
	background: #fff;
}

.bang {
	background-color: #fff;

	.tou {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin: 0 20rpx;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}
}

.self {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	border: 1rpx solid #ccc;

	.btn {
		padding: 10rpx 30rpx;
		background-color: #f4654c;
		color: #fff;
		border-radius: 10rpx;
	}
}

.tou-text {
	width: 100%;
	height: 100%;
	text-align: center;
	line-height: 80rpx;
	font-size: 28rpx;
	background-color: #f4654c;
	color: #fff;
	border-radius: 50%;
}
</style>
